package com.dlc.felear.xiaoensale.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.entity.ApkversionInfo;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.itdlc.android.library.utils.APPDidUtil;
import com.itdlc.android.library.utils.AppInfo;
import com.itdlc.android.library.utils.FileUtil;
import com.itdlc.android.library.utils.SilentInstall;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class UpLoadAPK {
    private static final String TAG = "UpLoadAPK";
    /**
     * 上下文
     */
    private Context context;
    /**
     * 1弹簧机 2重力机售卖机 3刷脸设备 4刷卡机 10云端称 11配菜计量台 20 炒菜机器人
     */
    private String clienttype="20";
    /**
     * 单例实体
     */
    private static UpLoadAPK instance;
    /**
     * 设备编码
     */
    private String deviceId;
    /**
     * 当前版本号信息
     */
    private float currentVersion;
    /**
     * 是否正在下载标志位
     */
    private boolean isDownLoad = false;
    /**
     * 本地路径
     */
    String filePath = Constant.APK_PATH;
    private DownloadStatusCallback callback;

    public void setCallback(DownloadStatusCallback callback) {
        this.callback = callback;
    }

    public UpLoadAPK setDeviceId(String deviceId) {
        this.deviceId = deviceId;
        return instance;
    }

    public UpLoadAPK(Context context) {
        this.context = context;
        try {
            currentVersion = Float.parseFloat(AppInfo.getLocalVersionName(context));
            updateVersionStatus(currentVersion - 0.1f);
            isDownLoad = false;
        } catch (Exception e) {
            currentVersion = 0.0f;
        }

    }

    public static UpLoadAPK getInstance(Context context) {
        if (instance == null) {
            synchronized (UpLoadAPK.class) {
                if (instance == null) {
                    instance = new UpLoadAPK(context);
                }
            }
        }
        return instance;
    }

    public void upLoadApkInfo(boolean flag) {
        getUrl();
    }

    private void getUrl() {
        if (isDownLoad) {
            sendPushMsg("正在下载，请稍等");
            return;
        }
        isDownLoad = true;
        Map<String, Object> params = new HashMap<>();
        params.put("terminalcode", APPDidUtil.getAppDid());
        params.put("clienttype", clienttype);
        params.put("version", currentVersion);
        Log.e(TAG,"请求参数:"+JsonHelper.toJson(params));
        OkHttpManager.HttpPostJson(HttpApi.URL_VERSION_UPDATE, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                isDownLoad = false;
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    MyLog.e(TAG, "版本信息" + response);
                    ApkversionInfo result = JsonHelper.parserJson(response, ApkversionInfo.class);
                    if (result != null && result.getCode() == 200 && result.getData() != null) {
                        if (ignoreVesion(AppInfo.getLocalVersionName(context), result.getData().getClientversion())) {
                            sendPushMsg("忽略该本版："+result.getData().getClientversion());
                            updateVersionStatus(currentVersion);
                            return;
                        }
                        downloadAndInstall(result.getData().getUrl(), result.getData().getBytesize());
//                        if (Float.parseFloat(result.getData().getClientversion()) > currentVersion) {
//                            downloadAndInstall(result.getData().getUrl(), result.getData().getBytesize());
//                        } else {
//                            isDownLoad = false;
//                            updateVersionStatus(Float.parseFloat(result.getData().getClientversion()));
//                            sendPushMsg("已是最新版本");
//                            deleteApk();
//                        }
                    } else {
                        isDownLoad = false;
                        MyLog.e(TAG, "没有发布新版本");
                        sendPushMsg("没有发布新版本");
                    }
                } catch (Exception e) {
                    isDownLoad = false;
                }
            }
        });
    }


    private boolean ignoreVesion(String localVersion, String cloudVersion) {
//        if (TextUtils.equals(localVersion, "1.28") && TextUtils.equals(cloudVersion, "1.31")) {
//            return true;
//        }
        return false;
    }

    /**
     * 下载安装包
     *
     * @param url      资源文件
     * @param byteSize 文件大小
     */
    private void downloadAndInstall(String url, long byteSize) {
        if(TextUtils.isEmpty(url)){
            sendPushMsg("升级文件不存在："+url);
            isDownLoad=false;
            return;
        }
        sendPushMsg("开始下载："+url);
        down(HttpApi.APK_URL + url, url, byteSize);
    }

    private void down(String urlStr, String name, final long byteSize) {
        FileUtil.createFilePath(filePath);
        boolean isExist = FileUtil.checkFileIsExist(filePath + name);
        if (isExist) {
            //本地存在apk，直接安装apk
            MyLog.e(TAG, "本地存在apk，直接安装apk");
            installApk(new File(filePath + name), byteSize);
        } else {
            sendPushMsg("正在下载");
            //本地不存在apk，网络下载
            OkHttpManager.HttpGet(urlStr, new FileCallBack(filePath, name) {
                @Override
                public void onError(Call call, Exception e, int id) {
                    MyLog.e(TAG, "apk下载错误");
                    Toast.makeText(context,"下载出错:"+e.getMessage(),Toast.LENGTH_SHORT).show();
                    isDownLoad = false;
                }

                @Override
                public void onResponse(File file, int id) {
                    isDownLoad = false;
                    if (file != null) {
                        installApk(file, byteSize);
                    } else {
                        sendPushMsg("apk下载不完整");
                        MyLog.e(TAG, "apk下载不完整");
                    }
                }

                @Override
                public void inProgress(float progress, long total, int id) {
                    if(callback!=null){
                        callback.downloadStatusCallback(progress,total,id);
                    }
                }
            });
        }

    }

    /**
     * 静默安装
     *
     * @param apk      本地文件
     * @param fileSize 文件大小
     */
    private void installApk(File apk, long fileSize) {
        isDownLoad = false;
        MyLog.e(TAG, "开始安装 " + "fileSize= " + fileSize + " apksize=" + apk.length());
        if (apk.length() == fileSize ) {
            MyLog.e(TAG, "开始安装 ");
            sendPushMsg("开始安装");
            SilentInstall install = new SilentInstall();
            install.installApk(context,apk);
//            install.install(context, apk.getAbsolutePath());
        } else if (apk.length() != fileSize) {
            MyLog.e(TAG, "安装失败，文件受损 ");
            sendPushMsg("安装失败,文件校验通过: " + apk.length() + "," + fileSize);
            apk.delete();
        }
    }


    /**
     * 更新状态
     */
    private void updateVersionStatus(float newVersion) {
        if (currentVersion <= newVersion) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("status", "1");
        map.put("statusdesc", "升级成功");
        map.put("clientversion", currentVersion);
        map.put("terminalcode", APPDidUtil.getAppDid());
        map.put("clienttype", clienttype);
        OkHttpManager.HttpPostJson(HttpApi.URL_VERSION_UPDATE_STATUS, map, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyLog.e(TAG, "更新版本状态=错误");
            }

            @Override
            public void onResponse(String response, int id) {
                MyLog.e(TAG, "更新版本状态=" + response);
            }
        });
    }


    private void sendPushMsg(String msg) {
        if(callback!=null){
            callback.apkVersionMsg(msg);
        }
    }

    private void sendLog(String log) {
        Log.e(TAG, log);
        sendPushMsg(log);
    }

    private void deleteApk() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    screnFile();
                } catch (Exception e) {

                }
            }
        }).start();
    }

    /**
     * 删除本地文件apk
     */
    private void screnFile() {
//        File file = new File(filePath);
//        for (String path : file.list()) {
//            File temp = new File(filePath, path);
//            if (temp.isFile() && path.endsWith(".apk")) {
//                temp.delete();
//            } else {
//                continue;
//            }
//        }
    }

    public interface DownloadStatusCallback{
        void downloadStatusCallback(float progress, long total, int id);
        void apkVersionMsg(String msg);
    }

}
